import {Component, ComponentFactoryResolver, Input, QueryList, ViewChildren, ViewContainerRef} from '@angular/core';
import {CommonPage} from '../../common-page';
import {DhlInputComponent} from '../../../../shared/components/dhlcomponent/input/dhl-input.component';
import {ObjectUtil} from '../../../../shared/utils/object-util';

@Component({
  selector: 'dhl-action-form',
  templateUrl: './action.form.component.html'
})
export class ActionFormComponent extends CommonPage {

  inputList = [];
  @Input() id;
  @Input() name;
  @Input() url;
  @Input() code;
  @Input() icon;
  @Input() nodeId;
  @Input() projectId;
  @Input() checkedMenuId;
  @Input() menuNodeId;
  @Input() menuNodeName;


  @Input() set inputUrl(values) {

    if (!ObjectUtil.isHaveValue(values)) {
      this.inputList = [];
      return;
    }
    const inputs = [];
    for (let i = 0; i < values.length; i++) {
      inputs.push({index: i});
    }
    this.inputList = inputs;

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DhlInputComponent);
    setTimeout(() => {
      for (let i = 0; i < this.inputList.length; i++) {
        const viewRef = this.templateList.filter((p, j) => j == i)[0];
        const instance = viewRef.createComponent(componentFactory).instance;
        instance.name = 'url';
        instance.code = `url`;
        instance.value = values[i];
        instance.labelWidth = 7;
      }
    }, 50);
  }


  @ViewChildren('inputTemplate', {read: ViewContainerRef}) templateList: QueryList<ViewContainerRef>;


  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    super();
  }

  reduce({index}) {
    this.inputList.splice(index, 1);
  }

  plus() {

    const lastIndex = this.inputList.length > 0 ? this.inputList[this.inputList.length - 1].index : -1;
    this.inputList.push({index: lastIndex + 1});
    setTimeout(() => {
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DhlInputComponent);
      const viewRef = this.templateList.filter((p, j) => j == this.templateList.length - 1)[0];
      viewRef.clear();
      const instance = viewRef.createComponent(componentFactory).instance;
      instance.name = 'url';
      instance.code = `url`;
      instance.labelWidth = 7;
    }, 100);
  }

}




